//
//  ContactInfoViewController.m
//  DanaKreditLoan
//
//  Created by ZhengChengFeng on 2024/10/21.
//

#import "ContactInfoViewController.h"
#import "EmergencyTableViewCell.h"
#import "SinglePickerView.h"

#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>

#import <Contacts/CNContactStore.h>
#import <ContactsUI/CNContactPickerViewController.h>

#import "OrderDetailModel.h"
#import "IdCardVertifyModel.h"
#import "IdCardViewController.h"
#import "IdCardFaceViewController.h"
#import "IdCardSuccessViewController.h"
#import "PersonInfoViewController.h"
#import "BankCardInfoViewController.h"

#define kTabCell    @"kTabCell"

@interface ContactInfoViewController ()<CNContactPickerDelegate,CLLocationManagerDelegate>
@property (nonatomic) OrderDetailModel *orderDetModel;


@property (nonatomic) EmergencyModel *md;

@property (nonatomic) BOOL isEnterContact;


@property (nonatomic) CLLocationManager *locationManager;
@property (nonatomic) NSTimer *timer;
@property (nonatomic) NSInteger timeInt;
@property (nonatomic) BOOL isLocationSuccess;
@property (nonatomic) NSString *startTimeStr1,*endTimeStr1;

@property (nonatomic) NSInteger type;

@property (nonatomic) CLLocationManager *locationManager2;
@property (nonatomic) NSTimer *timer2;
@property (nonatomic) NSInteger timeInt2;
@property (nonatomic) BOOL isLocationSuccess2;
@property (nonatomic) NSString *startTimeStr2,*endTimeStr2;

@end

#define kFootViewHeight  (15 + 48 + (IS_IPhoneX_All ? kHeight_BottomSafe : 15))

@implementation ContactInfoViewController

- (void)back{
    [[DKCore sharedDKCore] jumpWLAlertView:^{
        [[self getCurrentVC] jumpToPopControlClass:@"OrderDetailViewController"];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.startTimeStr1 = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
}


- (void)initFootView{

    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kFootViewHeight - kNavigationBarHeight, kScreenWidth, kFootViewHeight)];
    bottomV.backgroundColor = kTableViewBackColor;
    [self.view addSubview:bottomV];
    
    
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 15, kScreenWidth - 30, 48)];
    nextBtn.titleLabel.font = [UIFont fontWithName:kFuturaMedium size:16];
    [nextBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [nextBtn setTitleColor:kWhiteColor forState:UIControlStateSelected];
    [nextBtn setTitleColor:kWhiteColor forState:UIControlStateHighlighted];
    [nextBtn setTitle:ASLocalizedString(@"Submit") forState:UIControlStateNormal];
    [nextBtn setTitle:ASLocalizedString(@"Submit") forState:UIControlStateSelected];
    [nextBtn setTitle:ASLocalizedString(@"Submit") forState:UIControlStateHighlighted];
    [nextBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateNormal];
    [nextBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateSelected];
    [nextBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateHighlighted];
    [nextBtn addTarget:self action:@selector(clickSubmitBtn) forControlEvents:UIControlEventTouchUpInside];
    nextBtn.backgroundColor = kButtonDefaultColor;
    nextBtn.layer.cornerRadius = 24;
    nextBtn.layer.masksToBounds = YES;
    [bottomV addSubview:nextBtn];
    [nextBtn setImgRightTitltLeft:10];

}

- (void)initHeadView{
    UIView *headV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(220))];
    self.tableView.tableHeaderView = headV;
    
    UIImageView *imgV1 = [[UIImageView alloc] initWithFrame:CGRectMake(20, DimensionBaseIphone6(53), kScreenWidth - 40, DimensionBaseIphone6(118))];
    [headV addSubview:imgV1];
    imgV1.image = [UIImage imageNamed:@"icon_idcard1"];
    
    UIImageView *imgV2 = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - DimensionBaseIphone6(184))/2, DimensionBaseIphone6(20), DimensionBaseIphone6(184), DimensionBaseIphone6(184))];
    [headV addSubview:imgV2];
    imgV2.image = [UIImage imageNamed:@"icon_emergency"];
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.    
    self.isEnterContact = NO;
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kFootViewHeight );
    [self loadData];
    [self.tableView registerClass:[EmergencyTableViewCell class] forCellReuseIdentifier:kTabCell];
}

- (void)loadData{
    
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"largely":esString(self.idStr),
    }.mutableCopy;
    [HttpNetHelper postNetworkHelperForPath:kEmergencyUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        
        [self initHeadView];
        [self initFootView];
        NSDictionary *dic = responseDic[@"clip"][@"stolen"];
        if (isArray(dic[@"continuing"])) {
            NSArray *arr = dic[@"continuing"];
            self.data = [EmergencyModel mj_objectArrayWithKeyValuesArray:arr];
        }
        [self.tableView reloadData];
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
    } withIsForm:YES];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    EmergencyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.data.count > 0) {
        cell.model = self.data[indexPath.section];
        cell.topNameLab.text = [NSString stringWithFormat:@"%@%ld",ASLocalizedString(@"Emergency Contacts"),indexPath.row + 1];
        
        NSArray *arr = cell.model.ysabel;
        for (int i =0; i<arr.count; i++) {
            ApprehendModel *md = [ApprehendModel mj_objectWithKeyValues:arr[i]];
            if ([cell.model.navigated isEqualToString:md.lord]) {
                cell.textFiled1.text = esString(md.hydrogen);
            }
        }
        
    }
    
        
    cell.clickTap1Block = ^(EmergencyModel * _Nonnull mm) {
                
        NSArray *appArr = mm.ysabel;
        NSMutableArray *singArr = [[NSMutableArray alloc] init];
        NSMutableArray *lordArr = [[NSMutableArray alloc] init];
        for (int i=0; i<appArr.count; i++) {
            ApprehendModel *md = [ApprehendModel mj_objectWithKeyValues:appArr[i]];
            [singArr addObject:md.hydrogen];
            [lordArr addObject:md.lord];
        }
        
        SinglePickerView *pickView = [[SinglePickerView alloc]init];
        for (int i = 0; i<singArr.count; i++) {
            if ([mm.navigated isEqualToString:lordArr[i]]) {
                pickView.selectInteger = i;
               
            }
        }
        [pickView pickViewWithArray:singArr andTitleStr:ASLocalizedString(@"Emergency1Str")];
        [pickView showBottomView];
        [[UIApplication sharedApplication].keyWindow addSubview:pickView];
        
        pickView.block = ^(NSString *singleTitleString) {
            
            if ([singleTitleString isEqualToString:esString(mm.hydrogen)]) {
                return;
            }
            
            mm.relatedName = esString(singleTitleString);
            for (int i=0; i<appArr.count; i++) {
                ApprehendModel *md = [ApprehendModel mj_objectWithKeyValues:appArr[i]];
                if ([md.hydrogen isEqualToString:singleTitleString]) {
                    mm.navigated = md.lord;
                    break;
                }
            }
            
            
            
            [self.tableView reloadData];

        };
        
        
        
        
    };
    
    cell.clickTap2Block = ^(EmergencyModel * _Nonnull mm) {
        self.md = mm;
        
        if (![AuthorHelper isOpenContact]) {
            return;
        }
        
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
       
        if (status == CNAuthorizationStatusNotDetermined){
            CNContactStore *store = [[CNContactStore alloc] init];
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    [self jumpContact];
                }
            }];
        }
        else{
            [self jumpContact];
        }
    };
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 247;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc] init];
    return sectionView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc] init];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 15.00001f;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


- (void)jumpContact{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        CNContactPickerViewController *peoleVC = [[CNContactPickerViewController alloc] init];
        
        peoleVC.delegate = self;
        
        [self presentViewController:peoleVC animated:YES completion:^{
            [self getAllContactPhoneAndName];
        }];
        
    });
    
}

- (void)getAllContactPhoneAndName{
    if (self.isEnterContact) {
        return;
    }
    
    NSMutableArray *muArr = [[NSMutableArray alloc] init];
    
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
            
            NSMutableDictionary *muDict = [[NSMutableDictionary alloc]init];
            
            NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.givenName,contact.familyName];
            [muDict setValue:esString(nameStr) forKey:@"hydrogen"];
            
            NSMutableArray *phoneArr = [[NSMutableArray alloc] init];
            for (CNLabeledValue *phoneNumber in contact.phoneNumbers) {
                CNPhoneNumber *mobileStr = phoneNumber.value;
                [phoneArr addObject:[mobileStr.stringValue stringByReplacingOccurrencesOfString:@" " withString:@""]];
            }
            NSString *mobileS = [phoneArr componentsJoinedByString:@","];
            [muDict setValue:mobileS forKey:@"translated"];
            
            [muArr addObject:muDict];
        }];
        
        [self uploadContactData:muArr];
        
    });
    
    
    
}

#pragma mark ---uploadContactData
- (void)uploadContactData:(NSMutableArray *)muArr{
    
    [DataCategoryUpload uploadDataEmergencyContactInfo:muArr withResult:^{
        self.isEnterContact = YES;
    }];
    
}

- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact{
    
    self.md.hydrogen = [NSString stringWithFormat:@"%@%@",esString(contact.givenName),esString(contact.familyName)];
    
    if (contact.phoneNumbers.count > 0) {
        NSArray *phoneArr = contact.phoneNumbers;
        for (CNLabeledValue *labValue in phoneArr) {
            CNPhoneNumber *pn = labValue.value;
            NSString *phoneValue = pn.stringValue;
            if (!PMStringIsEmpty(phoneValue)) {
                self.md.quinine = esString(phoneValue);
                break;;
            }
        }
    }
    
    if (PMStringIsEmpty(self.md.cristoval) || contact.phoneNumbers.count == 0) {
        
        if (PMStringIsEmpty(self.md.hydrogen)) {
            [BoxLoadingHelper showBoxWithMessage:@"The name is incorrect,please select again."];
        }
        else{
            [BoxLoadingHelper showBoxWithMessage:@"The phone number is incorrect,please select again."];
        }
        
        self.md.hydrogen = @"";
        self.md.quinine = @"";
    }
    
    [self.tableView reloadData];
}

#pragma mark ----Submit
- (void)clickSubmitBtn{
    [self.view endEditing:YES];
    
    NSMutableDictionary *muDic = [NSMutableDictionary dictionary];
    [muDic setValue:esString(self.idStr) forKey:@"largely"];

    NSMutableArray *muArr = [[NSMutableArray alloc] init];

    for (int i=0; i<self.data.count; i++) {
        EmergencyModel *mm = [EmergencyModel mj_objectWithKeyValues:self.data[i]];
        NSMutableDictionary *recDic = [[NSMutableDictionary alloc] init];
        [recDic setValue:esString(mm.quinine) forKey:@"quinine"];
        [recDic setValue:esString(mm.hydrogen) forKey:@"hydrogen"];
        [recDic setValue:esString(mm.navigated) forKey:@"navigated"];
        [recDic setValue:esString(mm.cristoval) forKey:@"cristoval"];
        [muArr addObject:recDic];
    }
    
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:muArr options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    [muDic setValue:jsonString forKey:@"clip"];    
    
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    
    [HttpNetHelper postNetworkHelperForPath:kSaveEmergencyUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        self.endTimeStr1 = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
        [self uploadMaiDianEmergencyInfoData];
        
        [self enterNextPage];
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
    } withIsForm:YES];
    
    
}

- (void)enterNextPage{
    
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"largely":esString(self.idStr),
        @"mainland":@"mainlandOrderDet",
    }.mutableCopy;
    [HttpNetHelper postNetworkHelperForPath:kOrderDetailUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
    
      
        NSDictionary *dic = responseDic[@"clip"];
       
        OrderDetailModel *model = [OrderDetailModel mj_objectWithKeyValues:dic];
        self.orderDetModel = model;
        
        if (PMObjectIsEmpty(model.swears)) {
            [self enterOrderH5Page];
            return;
        }
        if ([esString(model.swears.undiluted) isEqualToString:kIdCardInfoVertify]) {
            [self goIdCardVertify];
        }
        else if ([esString(model.swears.undiluted) isEqualToString:kPersonInfoVertify]) {
            [self goPersonalVertify];
        }
        else if ([esString(model.swears.undiluted) isEqualToString:kBankInfoVertify]) {
            [self goBankVertify];
        }

        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
    } withIsForm:YES];
    

}
    

- (void)enterOrderH5Page{
        NSMutableDictionary *muDic = @{
            @"dosed":esString(self.orderDetModel.refugees.passages),
            @"founders":esString(self.orderDetModel.refugees.founders),
            @"weakness":esString(self.orderDetModel.refugees.weakness),
            @"shouldered":esString(self.orderDetModel.refugees.shouldered),
            @"guiding":@"guidingIdStr",
            @"excuse":@"excuseIdStr",
        }.mutableCopy;
    self.startTimeStr2 = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
        [BoxLoadingHelper showBoxLoadingWithMessage:@""];
        [HttpNetHelper postNetworkHelperForPath:kOrderNoUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
            [BoxLoadingHelper hideBoxLoading];
            if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
                [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
                return;
            }
        
            self.endTimeStr2 = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
            [self uploadMaiDianSDStartData];
            
            NSDictionary *dic = responseDic[@"clip"];
            
            [[DKCore sharedDKCore] jumpToControllerWithUrlString:esString(dic[@"twentieth"])];
          
        } onCompleteFailur:^(NSError * _Nonnull error) {
            [BoxLoadingHelper hideBoxLoading];
        } withIsForm:YES];
        
}


- (void)goIdCardVertify{
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"largely":esString(self.idStr),
        @"enabled":@"enabledIdCard"
    }.mutableCopy;
    [HttpNetHelper getNetworkHelperForPath:kGetIdCardInfoUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        
        NSDictionary *dic = responseDic[@"clip"];
        
        IdCardVertifyModel *model = [IdCardVertifyModel mj_objectWithKeyValues:dic];
        
        
        if ([model.ego.keller integerValue] == 0) {
            IdCardViewController *vc = [[IdCardViewController alloc] init];
            vc.idStr = esString(self.idStr);
            vc.orderNoStr = esString(self.orderDetModel.refugees.passages);
            vc.title = esString(self.orderDetModel.swears.arrow);
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        else if ([model.immunity.keller integerValue] == 0 ){
            IdCardFaceViewController *vc = [[IdCardFaceViewController alloc] init];
            vc.idStr = esString(self.idStr);
            vc.orderNoStr = esString(self.orderDetModel.refugees.passages);
            vc.title = esString(self.orderDetModel.swears.arrow);
            [self.navigationController pushViewController:vc animated:YES];
        }
        else{
            IdCardSuccessViewController *vc = [[IdCardSuccessViewController alloc] init];
            vc.nameStr = esString(model.ego.pureness.hydrogen);
            vc.idNoStr = esString(model.ego.pureness.shyly);
            vc.birDateStr = esString(model.ego.pureness.flattered);
            vc.idStr = esString(self.idStr);
            vc.orderNoStr = esString(self.orderDetModel.refugees.passages);
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
    } withIsForm:NO];
    
}


- (void)goPersonalVertify{
    PersonInfoViewController *vc = [[PersonInfoViewController alloc] init];
    vc.idStr = esString(self.idStr);
    vc.orderNoStr = esString(self.orderNoStr);
    vc.title = esString(self.orderDetModel.swears.arrow);
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)goBankVertify{
    BankCardInfoViewController *vc = [[BankCardInfoViewController alloc] init];
    vc.idStr = esString(self.idStr);
    vc.orderNoStr = esString(self.orderNoStr);
    vc.title = esString(self.orderDetModel.swears.arrow);
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark ----- uploadMaiDianEmergencyInfoData -------
- (void)uploadMaiDianEmergencyInfoData{
    self.timeInt = 0;
    self.isLocationSuccess = NO;
    [self initLocation];
}

- (void)initLocation{
    self.timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(addTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestLocation];
}

- (void)addTimer{
    self.timeInt ++;
    if (self.isLocationSuccess) {
        [self.timer invalidate];
        self.timer = nil;
        self.timeInt = 0;
    }
    else{
        if (self.timeInt > 8) {
            [self.timer invalidate];
            self.timer = nil;
            self.timeInt = 0;
            NSString *longitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLongitude];
            NSString *latitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLatitude];
            
            [self goServer1WithLongitudeStr:PMStringIsEmpty(longitudeStr) ? @"" : longitudeStr withLatitudeStr:PMStringIsEmpty(latitudeStr) ? @"" : latitudeStr];
            
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *newlocation = locations[0];
    NSString *longitudeStr = [NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude];
    NSString *latitudeStr =  [NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude];
    
    if (manager == self.locationManager) {
        [self.locationManager stopUpdatingLocation];
    } else {
        [self.locationManager2 stopUpdatingLocation];
    }
    
    
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude] forKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude] forKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (self.type == 2) {
        self.isLocationSuccess2 = YES;
        
        if (self.timeInt2 <= 8) {
            [self goServer2WithLongitudeStr:esString(longitudeStr) withLatitudeStr:esString(latitudeStr)];
        }
        
    } else {
        self.isLocationSuccess = YES;
        
        if (self.timeInt <= 8) {
            [self goServer1WithLongitudeStr:esString(longitudeStr) withLatitudeStr:esString(latitudeStr)];
        }
    }

}

- (void)goServer1WithLongitudeStr:(NSString *)longitudeStr withLatitudeStr:(NSString *)latitudeStr{
    [DataCategoryUpload uploadMaiDianData:@"6" withOrderIdStr:self.idStr withOrderNoStr:esString(self.orderNoStr) withLongitude:esString(longitudeStr) withLatitude:esString(latitudeStr) withStartTime:self.startTimeStr1 withEndTime:self.endTimeStr1];
}

- (void)goServer2WithLongitudeStr:(NSString *)longitudeStr withLatitudeStr:(NSString *)latitudeStr{
    [DataCategoryUpload uploadMaiDianData:@"8" withOrderIdStr:self.idStr withOrderNoStr:esString(self.orderNoStr) withLongitude:esString(longitudeStr) withLatitude:esString(latitudeStr) withStartTime:self.startTimeStr2 withEndTime:self.endTimeStr2];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}


#pragma mark ----- uploadMaiDianSDStartData ------
- (void)uploadMaiDianSDStartData{
    self.type = 2;
    self.timeInt2 = 0;
    self.isLocationSuccess2 = NO;
    [self initLocation2];
}

- (void)initLocation2{
    
    self.timer2 = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(addTimer2) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer2 forMode:NSRunLoopCommonModes];
    
    self.locationManager2 = [[CLLocationManager alloc]init];
    self.locationManager2.delegate = self;
    self.locationManager2.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager2.distanceFilter = 100;
    [self.locationManager2 requestWhenInUseAuthorization];
    [self.locationManager2 requestLocation];
}

- (void)addTimer2{
    self.timeInt2 ++;
    if (self.isLocationSuccess2) {
        [self.timer2 invalidate];
        self.timer2 = nil;
        self.timeInt2 = 0;
    }
    else{
        if (self.timeInt2 > 8) {
            [self.timer2 invalidate];
            self.timer2 = nil;
            self.timeInt2 = 0;
            NSString *longitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLongitude];
            NSString *latitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLatitude];
            
            [self goServer2WithLongitudeStr:PMStringIsEmpty(longitudeStr) ? @"" : longitudeStr withLatitudeStr:PMStringIsEmpty(latitudeStr) ? @"" : latitudeStr];
            
        }
    }
}


@end


